package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {

	@Autowired
	CheckGroupDao checkGroupDao;

	@Override
	@Transactional
	public void add(CheckGroup checkGroup, Integer[] checkitemIds) {


		//需要主键回显
		checkGroupDao.add(checkGroup);


		if(checkGroup.getId()!=null&&checkitemIds!=null&&checkitemIds.length>0){

			for (Integer checkitemId:checkitemIds
				 ) {
				checkGroupDao.addRelation(checkGroup.getId(),checkitemId);
			}



		}

	}

	@Override
	public PageResult findPage(QueryPageBean queryPageBean) {

		PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

		Page<CheckGroup> page = checkGroupDao.findPage(queryPageBean.getQueryString());

		return new PageResult(page.getTotal(),page);
	}

	@Override
	public void delById(Integer id) {

		long count = checkGroupDao.findCountById(id);

		if(count>0){

			throw new RuntimeException("该检查组和套餐关联,不能被删除");

		}

		checkGroupDao.delCheckItemRelation(id);
		checkGroupDao.delById(id);



	}

	@Override
	public CheckGroup findById(Integer id) {
		return checkGroupDao.findById(id);
	}

	@Override
	public Integer[] findCheckItemIdsById(Integer id) {


		return checkGroupDao.findCheckItemIdsById(id);
	}

	@Override
	@Transactional
	public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {

		checkGroupDao.edit(checkGroup);

		checkGroupDao.delCheckItemRelation(checkGroup.getId());

		if(checkGroup.getId()!=null&&checkitemIds!=null&&checkitemIds.length>0){

			for (Integer checkitemId:checkitemIds
					) {
				checkGroupDao.addRelation(checkGroup.getId(),checkitemId);
			}
		}
	}

	@Override
	public List<CheckGroup> findAll() {


		return checkGroupDao.findAll();
	}
}
